package qit.itmiaojie.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import qit.itmiaojie.dao.RoleDao;
import qit.itmiaojie.dao.UserDao;
import qit.itmiaojie.pojo.Role;
import qit.itmiaojie.pojo.User;
import qit.itmiaojie.service.UserService;

import java.util.List;

public class UserServiceImpl implements UserService {
    private UserDao userDao;
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Autowired
    private RoleDao roleDao;

    @Override
    public List<User> findAll() {
        List<User> userList = userDao.findAll();
        for (User user : userList) {
            Long id = user.getId();
            List<Role> roleList = roleDao.findRoleByUserId(id);
            user.setRoleList(roleList);
        }
        return userList;
    }

    /**
     * 新增用户
     * @param user
     * @param roleIds
     */
    @Override
    public void save(User user, long[] roleIds) {
        Long id = userDao.saveUser(user);
        userDao.saveUIdAndRId(id,roleIds);
    }

    @Override
    public void del(Long id) {
        //先删除关系表
        userDao.delUserAndRoleTable(id);
        //然后在删除用户表
        userDao.delUser(id);
    }

    @Override
    public User login(String username, String password)  {
        User user = userDao.findByUsernameAndPassword(username, password);
        if (user == null){
            return null;
        }
        return user;
    }


}
